package com.xm.redis.redisson;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Slf4j
@Component
//@Service
public class LockExample {
    @Resource(name = "redissonClient")
    private RedissonClient redissonClient;

    /**
     * 公平锁示例
     */
    public void fairLock() {
        String lockKey = "fairLock";
        RLock fairLock = redissonClient.getFairLock(lockKey);

        try {
            fairLock.lock();
            log.info("fair lock ok");
        } finally {
            fairLock.unlock();
        }
    }

    /**
     * 联锁示例
     */
    public void multiLock() {
        String lockKey = "multiLock1";
        RLock lock1 = redissonClient.getLock(lockKey);
        String lockKey2 = "multiLock2";
        RLock lock2 = redissonClient.getLock(lockKey2);
        RLock multiLock = redissonClient.getMultiLock(lock1, lock2);

        try {
            multiLock.lock();
            log.info("multi lock ok");
        } finally {
            multiLock.unlock();
        }
    }

    /**
     * 红锁示例
     */
    @Deprecated
    public void redLock() {
        String redKey = "redLock";
        // 配置多个独立 Redis 节点
        Config config1 = new Config();
        config1.useSingleServer().setAddress("redis://node1:6379");
        RedissonClient client1 = Redisson.create(config1);

        Config config2 = new Config();
        config2.useSingleServer().setAddress("redis://node2:6379");
        RedissonClient client2 = Redisson.create(config2);

        Config config3 = new Config();
        config3.useSingleServer().setAddress("redis://node3:6379");
        RedissonClient client3 = Redisson.create(config3);

        RLock lock1 = client1.getLock(redKey);
        RLock lock2 = client2.getLock(redKey);
        RLock lock3 = client3.getLock(redKey);

        RLock redLock = client1.getRedLock(lock1, lock2, lock3);

        try {
            redLock.lock();
            log.info("redLock ok");
        } finally {
            redLock.unlock();
        }
    }
}
